from django.db import models
from mlh.utils.models import BaseModel
from ckeditor.fields import RichTextField


class UserTags(models.Model):
    """
    标签关注表
    """
    user = models.ForeignKey("users.User", on_delete=models.CASCADE, verbose_name="用户id")
    tags = models.ForeignKey('Tags', on_delete=models.CASCADE, verbose_name='标签id')

    class Meta:
        db_table = "tb_user_tags"
        verbose_name = "标签关注表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s:%s" % (self.user.username, self.tags.name)


class Tags(models.Model):
    """
    标签表
    """
    name = models.CharField(max_length=32, verbose_name="标签名称")
    parent = models.ForeignKey("self", related_name="subs", verbose_name="父标签id", null=True, blank=True)
    introduction = models.CharField(max_length=256, verbose_name="标签介绍", default="")
    concern = models.IntegerField(default=0, verbose_name="关注数量")

    class Meta:
        db_table = "tb_tags"
        verbose_name = "标签表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s" % self.name


class QuestionTag(models.Model):
    """
    问题标签关系表
    """
    question = models.ForeignKey("Question", on_delete=models.CASCADE, verbose_name="问题id")
    tags = models.ForeignKey('Tags', on_delete=models.SET_NULL, blank=True, null=True, verbose_name='标签id')

    class Meta:
        db_table = "tb_question_tags"
        verbose_name = "问题标签关系表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s" % self.question.title


class Question(BaseModel):
    """
    问题表
    """
    title = models.CharField(max_length=64, verbose_name="问题标题")
    content = RichTextField(null=False, blank=False, verbose_name="问题内容")
    hits = models.IntegerField(default=0, verbose_name="浏览量")
    likes_count = models.IntegerField(default=0, verbose_name="点赞数量")
    answer_count = models.IntegerField(default=0, verbose_name="回答数量")
    last_answer_time = models.DateTimeField(verbose_name="最后回答时间", null=True, blank=True)
    user = models.ForeignKey("users.User", on_delete=models.PROTECT, verbose_name="提问用户id")

    class Meta:
        db_table = "tb_question"
        verbose_name = "问题表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s" % self.title


class Answer(BaseModel):
    """
    回答表
    """
    content = RichTextField(null=False, blank=False, verbose_name="回答内容")
    likes_count = models.IntegerField(default=0, verbose_name="点赞数量")
    reports = models.IntegerField(default=0, verbose_name="被举报次数")
    user = models.ForeignKey("users.User", on_delete=models.PROTECT, verbose_name="回答用户id")
    question = models.ForeignKey("Question", on_delete=models.CASCADE, verbose_name="问题id")

    class Meta:
        db_table = "tb_answer"
        verbose_name = "回答表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "回答:%s" % self.question.title






